<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\facade\Log;

/**
 * 关键应用接口
 */
class Es extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = [];

    public function flow()
    {
        //处理参数
        $ip = $this->request->post('ip');
        if(!$ip){
            $this->error(__('Missed parameters:ip'));
        }
        $starttime = $this->request->post('starttime');
        if(!$starttime){
            $starttime = date('Y-m-d H:i:s',time()-24*60*60);
        }
        $starttime = strtotime($starttime).'000';
        $endtime = $this->request->post('endtime');
        if(!$endtime){
            $endtime = date('Y-m-d H:i:s');
        }
        $endtime = strtotime($endtime).'000';
        $gradename = $this->request->post('gradename');
        if(!$gradename){
            $gradename = '5m';
        }
        //请求参数
        $data_string = '{
        "aggs": {
            "2": {
              "date_histogram": {
                "field": "endtime",
                "interval": "'.$gradename.'",
                "time_zone": "Asia/Shanghai",
                "min_doc_count": 1
              },
              "aggs": {
                "down": {
                  "sum": {
                    "field": "down"
                  }
                },
                "up": {
                  "sum": {
                    "field": "up"
                  }
                }
              }
            }
          },
          "size": 0,
          "_source": {
            "excludes": []
          },
          "stored_fields": [
            "*"
          ],
          "script_fields": {},
          "query": {
            "bool": {
              "must": [
                {
                  "match_phrase": {
                    "ip": {
                      "query": "'.$ip.'"
                    }
                  }
                },
                {
                  "range": {
                    "endtime": {
                      "gte": '.$starttime.',
                      "lte": '.$endtime.',
                      "format": "epoch_millis"
                    }
                  }
                }
              ],
              "filter": [
                {
                  "match_all": {}
                },
                {
                  "match_all": {}
                }
              ],
              "should": [],
              "must_not": []
            }
          }
        }';
        $result = $this->requst_es($data_string, 'aggs');
        $this->success('成功', $result);
    }
    /**
     * 请求es
     */
    public function requst_es($data_string, $type='aggs'){
      $url = config('es')['url'];
      $curlopt = array(
            CURLOPT_HTTPHEADER=>array ('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen ( $data_string ) ),
            CURLOPT_TIMEOUT=>config('es')['timeout'],
            CURLOPT_HTTPAUTH=>CURLAUTH_BASIC,
            CURLOPT_USERPWD => config('es')['user_pwd']
        );
        Log::record(microtime().'地址：'.$url,'API');
        Log::record(microtime().'参数：'.$data_string,'API');
        //发请求拿数据
        $data = curl_post($url, $data_string, $curlopt);
        Log::record(microtime().'返回：'.$data,'API');
        if(!$data){
            $this->error('es接口异常');
        }
        if(!is_json($data)){
            $this->error('es接口返回的不是JSON格式');
        }
        $arr = json_decode($data,true);
        // dump($arr);exit;
        if(isset($arr['error']) && $arr['error']){
            $this->error($arr['error']['reason']);
        }
        if($type == 'aggs'){
          if(!isset($arr['aggregations']['2']['buckets'])){
            $this->error('es接口返回数据为空');
          }
          $result = $arr['aggregations']['2']['buckets'];
        }else if($type == 'results'){
          $result = $arr['hits'];
        }else if($type == 'all'){
          $result = $arr;
        }
        if( ! ($result && count($result)>0 ) ){
            $this->error('es接口数据为空');
        }
        return $result;
    }
}
